import { createContext, useContext, useEffect, useState } from "react";
import { commonService, type SiteConfig } from "@/api/services/commonService";

interface ConfigContextType {
	config: SiteConfig | null;
	loading: boolean;
}

const ConfigContext = createContext<ConfigContextType>({
	config: null,
	loading: true,
});

export const ConfigProvider = ({ children }: { children: React.ReactNode }) => {
	const [config, setConfig] = useState<SiteConfig | null>(null);
	const [loading, setLoading] = useState(true);

	useEffect(() => {
		const fetchConfig = async () => {
			try {
				const data = await commonService.getConfig();
				setConfig(data);
			} catch (error) {
				console.error("获取配置失败:", error);
			} finally {
				setLoading(false);
			}
		};

		fetchConfig();
	}, []);

	return (
		<ConfigContext.Provider value={{ config, loading }}>
			{children}
		</ConfigContext.Provider>
	);
};

export const useConfig = () => {
	const context = useContext(ConfigContext);
	if (!context) {
		throw new Error("useConfig must be used within a ConfigProvider");
	}
	return context;
};
